//
//  transferViewController.m
//  BackgroundTaskSample
//  后台传输（下载/上传）
//  使用NSURLSession实现传输，传输是由iOS系统进行管理的，无时间限制
//  当应用在传输时被系统杀掉，系统会在后台控制传输的继续进行，当传输完成或至少一个任务需要应用的处理时，系统会适当的启动应用
//  当应用在传输时被用户杀掉，系统会取消所有挂起的任务
//  1.创建NSURLSessionConfiguration
//  2.创建NSURLSession
//  3.启动传输
//  Created by moliya on 16/4/23.
//  Copyright © 2016年 Wanquan Network Technology. All rights reserved.
//

#import "transferViewController.h"
#import "AppDelegate.h"

@interface transferViewController ()<NSURLSessionDownloadDelegate>

@property (strong, nonatomic) NSURLSession *session;
@property (strong, nonatomic) NSURLSessionDownloadTask *downloadTask;

@end

@implementation transferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (NSURLSession *)backgroundSession
{
    //Use dispatch_once_t to create only one background session. If you want more than one session, do with different identifier
    static NSURLSession *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *configuration = nil;
        CGFloat sysVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (sysVersion >= 8.0f) { //iOS8 above
            configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.carefree.BackgroundTaskSample.BackgroundSession"];
        }else { //iOS 7
            configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.carefree.BackgroundTaskSample.BackgroundSession"];
        }
        configuration.sessionSendsLaunchEvents = YES; //默认为YES
        configuration.discretionary = YES;
        session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    });
    return session;
}

#pragma mark - 开始下载任务
- (IBAction) beginDownload
{
    NSURL *downloadURL = [NSURL URLWithString:@"http://www.kdatu.com/wp-content/uploads/2016/03/682189.jpg"];
    NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
    self.session = [self backgroundSession];
    self.downloadTask = [self.session downloadTaskWithRequest:request];
    [self.downloadTask resume];
}

#pragma mark - NSURLSession delegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSLog(@"Session %@ 已下载任务： %@ 到路径 %@\n",session, downloadTask, location);
    NSError *err = nil;
    
    //保存文件到需要的位置
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    //任务完成时执行
    NSLog(@"Session %@ 已完成任务：%@", session, task);
}

-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
    //任务全部完成时执行
    NSLog(@"任务已全部完成");
    //调用后台传输完成回调，此时系统会更新快照并终止应用
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    if (appDelegate.backgroundSessionCompletionHandler) {
        void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
        appDelegate.backgroundSessionCompletionHandler = nil;
        completionHandler();
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
